<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2 class="sidebar-title">在线教育平台</h2>
        <el-button icon="el-icon-menu" class="toggle-btn" @click="toggleSidebar"></el-button>
      </div>
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#0b1b33"
          text-color="#fff"
          active-text-color="#409EFF"
          :collapse="isSidebarCollapse"
          router
      >
        <el-menu-item index="/home">
          <el-icon><Menu /></el-icon>
          <span>课程管理</span>
        </el-menu-item>
        <el-menu-item index="/kgfl">
          <el-icon><Folder /></el-icon>
          <span>课程分类管理</span>
        </el-menu-item>
        <el-menu-item index="/stu">
          <el-icon><User /></el-icon>
          <span>学生管理</span>
        </el-menu-item>
        <el-menu-item index="/teacher">
          <el-icon><User /></el-icon>
          <span>教师管理</span>
        </el-menu-item>
        <el-menu-item index="/per">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapse': isSidebarCollapse }">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item>教师管理</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题与操作 -->
      <div class="page-header">
        <h1 class="page-title">教师列表</h1>
        <el-button type="primary" @click="handleAddTeacher">
          <el-icon><Plus /></el-icon>添加教师
        </el-button>
      </div>

      <!-- 搜索筛选区 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="state.searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input v-model="state.searchForm.keyword" placeholder="请输入教师姓名/工号搜索" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 教师列表 -->
      <el-card class="teacher-list-card">
        <el-table
            :data="teacherList"
            border
            stripe
            highlight-current-row
            row-key="id"
        >
          <el-table-column prop="id" label="工号"/>
          <el-table-column prop="real_name" label="姓名" />
<!--          <el-table-column prop="email" label="邮箱" width="80" />-->
          <el-table-column prop="gender" label="性">
            <template #default="scope">
              {{ scope.row.gender === 'male' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="courseCount" label="授课数量"/>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleEditTeacher(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteTeacher(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="state.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="state.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.total"
          />
        </div>
      </el-card>

      <!-- 添加/编辑教师对话框 -->
      <el-dialog
          :visible.sync="state.dialogVisible"
          title="教师信息"
          width="400px"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
      >
        <template #content>
          <el-form :model="state.formData" ref="formRef" label-width="120px">
            <el-form-item
                label="工号"
                prop="id"
                :rules="{ required: true, message: '请输入工号', trigger: 'blur' }"
            >
              <el-input v-model="state.formData.id" placeholder="请输入工号" clearable />
            </el-form-item>
            <el-form-item
                label="姓名"
                prop="name"
                :rules="{ required: true, message: '请输入姓名', trigger: 'blur' }"
            >
              <el-input v-model="state.formData.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="state.formData.age" :min="0" placeholder="请输入年龄" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="state.formData.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
                label="邮箱"
                prop="email"
                :rules="{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }"
            >
              <el-input v-model="state.formData.email" placeholder="请输入邮箱" clearable />
            </el-form-item>
            <el-form-item label="授课数量" prop="courseCount">
              <el-input-number v-model="state.formData.courseCount" :min="0" placeholder="请输入授课数量" />
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveTeacher">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import {
  Plus,
  Search,
  Edit,
  Delete,
  Refresh,
  Menu,
  Folder,
  User
} from '@element-plus/icons-vue';
import {
  ElMessage,
  ElMessageBox,
  ElForm,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElRadio,
  ElRadioGroup,
  ElPagination,
  ElCard,
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElButton
} from 'element-plus';
import request from "@/utils/request.js";

// 侧边栏相关状态
const isSidebarCollapse = ref(false);
const activeMenu = ref('teacher-management');
const toggleSidebar = () => {
  isSidebarCollapse.value = !isSidebarCollapse.value;
};

// 教师管理相关状态
const state = reactive({
  teacherList: [], // 教师列表数据
  total: 0, // 总记录数
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页显示数量
  searchForm: {
    keyword: '' // 搜索关键词
  },
  dialogVisible: false, // 对话框是否显示
  dialogTitle: '添加教师', // 对话框标题
  formData: {
    id: null,
    name: '',
    age: null,
    gender: 'male',
    email: '',
    courseCount: 0
  }
});

// 表单引用
const formRef = ref(null);
const  teacherList = ref([]);

// 获取教师列表数据
const fetchTeacherList = async () => {
  try {
    // const { keyword } = state.searchForm;
    const response = await request.get('/teachers/list');
    teacherList.value = response.data;
    // state.total = response.data.total;
  } catch (error) {
    ElMessage.error('获取教师列表失败: ' + error.message);
  }
};

onMounted(() => {
  fetchTeacherList();
});

// 搜索教师
const handleSearch = () => {
  state.currentPage = 1;
  fetchTeacherList();
};

// 重置搜索条件
const resetSearch = () => {
  state.searchForm.keyword = '';
  state.currentPage = 1;
  fetchTeacherList();
};

// 分页相关
const handleSizeChange = (newSize) => {
  state.pageSize = newSize;
  fetchTeacherList();
};

const handleCurrentChange = (newPage) => {
  state.currentPage = newPage;
  fetchTeacherList();
};

// 添加教师
const handleAddTeacher = () => {
  // 重置表单数据
  state.formData.id = null;
  state.formData.name = '';
  state.formData.age = null;
  state.formData.gender = 'male';
  state.formData.email = '';
  state.formData.courseCount = 0;
  state.dialogTitle = '添加教师';

  // 显示对话框
  state.dialogVisible = true;
};

// 编辑教师
const handleEditTeacher = (row) => {
  // 复制数据到表单
  state.formData.id = row.id;
  state.formData.name = row.name;
  state.formData.age = row.age;
  state.formData.gender = row.gender;
  state.formData.email = row.email;
  state.formData.courseCount = row.courseCount;
  state.dialogTitle = '编辑教师';

  // 显示对话框
  state.dialogVisible = true;
};

// 删除教师
const handleDeleteTeacher = (row) => {
  ElMessageBox.confirm(
      `确定要删除教师「${row.name}」吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await request.delete(`/api/teachers/${row.id}`);
      ElMessage.success('删除成功');
      fetchTeacherList();
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message);
    }
  });
};

// 保存教师（添加/编辑）
const saveTeacher = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (state.formData.id) {
          // 编辑操作
          await request.put(`/api/teachers/${state.formData.id}`, state.formData);
          ElMessage.success('更新成功');
        } else {
          // 新增操作
          await request.post('/api/teachers', state.formData);
          ElMessage.success('创建成功');
        }
        // 关闭对话框
        state.dialogVisible = false;
        fetchTeacherList();
      } catch (error) {
        ElMessage.error('保存失败: ' + error.message);
      }
    } else {
      ElMessage.error('请完善表单信息');
    }
  });
};

// 监听侧边栏折叠状态
watch(isSidebarCollapse, (newVal) => {
  // 可在此处添加侧边栏折叠后的额外逻辑
});
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #0b1b33;
  color: #fff;
  transition: width 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #1f334b;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.toggle-btn {
  background: transparent;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
}

.el-menu-vertical-demo {
  border-right: none;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  transition: margin-left 0.3s ease-in-out;
}

.sidebar-collapse {
  margin-left: 64px; /* 侧边栏折叠后，主内容区调整左边距 */
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 10px;
}

/* 页面标题与操作样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

/* 教师列表卡片样式 */
.teacher-list-card {
  margin-bottom: 20px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
}
</style>
